﻿using System;
using System.Collections.Generic;
using System.Drawing;

namespace Swsk33.GISEndExercise.Model
{
	/// <summary>
	/// 多边形类
	/// </summary>
	public class Polygon
	{
		private PointF[] points;

		/// <summary>
		/// 构成多边形的点
		/// </summary>
		public PointF[] Points { get => points; }

		/// <summary>
		/// 构造器依赖注入，传入点数组初始化
		/// </summary>
		/// <param name="points">传入点数组</param>
		public Polygon(PointF[] points)
		{
			this.points = points;
		}

		/// <summary>
		/// 构造器依赖注入，传入点列表初始化
		/// </summary>
		/// <param name="points">传入点列表</param>
		public Polygon(List<PointF> points)
		{
			this.points = points.ToArray();
		}

		/// <summary>
		/// 得到该多边形面积
		/// </summary>
		/// <returns>多边形面积</returns>
		public double GetArea()
		{
			double total = 0;
			Point origin = new Point(0, 0);
			Vector current, next;
			for (int i = 0; i < points.Length; i++)
			{
				current = new Vector(origin, points[i]);
				if (i == points.Length - 1)
				{
					next = new Vector(origin, points[0]);
				}
				else
				{
					next = new Vector(origin, points[i + 1]);
				}
				total = total + current.CrossProduct(next);
			}
			return Math.Abs(total / 2);
		}

		/// <summary>
		/// 使用垂距法压缩自身多边形
		/// </summary>
		/// <returns>压缩后的多边形</returns>
		public Polygon Compress()
		{
			// 阈值
			double min = 0.08;
			// 保留的点
			List<PointF> resultPoints = new List<PointF>();
			Line lastToNext;
			for (int i = 1; i < points.Length - 1; i++)
			{
				lastToNext = new Line(points[i - 1], points[i + 1]);
				// 大于阈值的保留
				if (lastToNext.GetPointToLineOffset(points[i]) >= min)
				{
					resultPoints.Add(points[i]);
				}
			}
			// 保留首尾点
			resultPoints.Insert(0, points[0]);
			resultPoints.Add(points[points.Length - 1]);
			return new Polygon(resultPoints);
		}
	}
}